//
//  SpotprintController.swift
//  swiftProject
//
//  Created by ZhangSai on 2021/7/1.
//

import UIKit

class SpotprintController: ZsBaseViewController , UITableViewDelegate, UITableViewDataSource, SpotBoottomViewDelegate,SpotInformationCellDelegate,SpotSubjoinServeCellDelegate {

    let SpotInformationIdentifier = "SpotInformationIdentifier"
    let SpotAddressIdentifier = "SpotAddressIdentifier"
    let SpotSubjoinServeIdentifier = "SpotSubjoinServeIdentifier"

    var spotInfocell:SpotInformationCell!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_expressDelivery)
        self.view.backgroundColor = UIColor.init(hexString: "#F3F3F3")
        let roleType = WLUserModel.getRoleType()
        if roleType.contains(where: { (obj) -> Bool in
            if obj as! Int == 7 {
                orderInfoModel.payType = 3
                return true
            } else {
                return false
            }
        }) {
            
        }
        HttpService.sharedHttpService().getDefaultAddressSuccess { (addressModel, state, error) in
            if self.sendInfoModel.name.count <= 0 {
                return
            }
            self.sendInfoModel = addressModel
            self.tableview.reloadData()
            //是否支持寄件判断
            let dicData:Dictionary = ["cityId":(self.sendInfoModel.cityId),"cityName":self.sendInfoModel.city,"operateType":(1),"regionId":(self.sendInfoModel.regionId),"regionName":self.sendInfoModel.region] as [String : Any]
            HttpService.sharedHttpService().getrecAndSendSupport(dicData: dicData) { (josn, state, error) in
                if state {
                    Constants.window?.hideAllToasts()
                } else {
                    Constants.window?.hideAllToasts()
                    Constants.window?.makeToast(error)
                }
            }
        }
        self.setUI()
    }
    
    func setUI() {
        self.view.addSubview(self.boottomView)
        self.view.addSubview(self.tableview)
        self.addConstraints()
    }
    
    func addConstraints() {
        self.boottomView.snp.makeConstraints { (make) in
            make.bottom.equalTo(self.view.snp.bottom).offset(0);
            make.width.equalTo(self.view.snp.width);
            make.height.equalTo(56 + Constants.xSafeBottomHeight);
        }
        self.tableview.snp.makeConstraints { (make) in
            make.top.equalTo(self.view.snp.top).offset(15);
            make.bottom.equalTo(self.boottomView.snp.top);
            make.left.equalTo(self.view.snp.left).offset(0);
            make.right.equalTo(self.view.snp.right).offset(0);
        }
    }
    
    func textFieldDidChange() {
        if !orderInfoModel.goodsName.isEmpty {
            self.boottomView.printBtn.setTitleColor(UIColor.init(hexString: "#333333"), for: .normal)
            boottomView.printBtn.backgroundColor = UIColor.init(hexString: "#FFD10A")
            boottomView.printBtn.isSelected = true
        } else {
            self.boottomView.printBtn.setTitleColor(UIColor.init(hexString: "#FFFFFF"), for: .normal)
            boottomView.printBtn.backgroundColor = UIColor.init(hexString: "#D6D6D6")
            boottomView.printBtn.isSelected = false
        }
    }
    
    func getFreightValueSuccess(finishedCallback:@escaping (_ isSuccess: Bool) ->())  {
        if sendInfoModel.name.count > 0 && receiveInfoModel.name.count > 0 && orderInfoModel.goodsName.count > 0 {
            var volume = orderInfoModel.goodsLength * orderInfoModel.goodsWidth * orderInfoModel.goodsHeight / 1728
            if volume > 0 {
                if volume > 16 {
                    volume = 16
                }
            } else {
                volume = 0
            }
            let dicData:Dictionary = ["deliverToGate":(orderInfoModel.deliveryWay == 0 ? 0 : 1),
                                      "fromCityId":(sendInfoModel.cityId),
                                      "fromRegionId":(sendInfoModel.regionId),
                                      "goodsSize":String.init(format: "%.2f", volume),
                                      "goodsWeight":(orderInfoModel.goodsWidth),
                                      "toCityId":(receiveInfoModel.cityId),
                                      "toRegionId":(receiveInfoModel.regionId)] as [String : Any]
            HttpService.sharedHttpService().getFreightValue(dicData: dicData) { (json, state, error) in
                if state {
                    let jsonData:Dictionary = json["data"].dictionary ?? Dictionary()
                    self.orderInfoModel.freightAmount = jsonData["baseFreight"]?.description ?? ""
                    self.orderInfoModel.standardTimerValue = jsonData["expectedDeliveryTime"]?.description ?? ""
                    self.orderInfoModel.expectedDays = jsonData["expectedDays"]?.int ?? 0
                    self.lookBillV.setOrderInfoModel(orderInfoModel: self.orderInfoModel)
                    self.boottomView.valueLab.text = "MMK " + self.orderInfoModel.getTotalFreight()
                    self.tableview.reloadData()
                    finishedCallback(true)
                } else {
                    Constants.window?.hideAllToasts()
                    Constants.window?.hideToastActivity()
                    Constants.window?.makeToast(error)
                    finishedCallback(false)
                }
            }
        }
    }
    
    func getcalculateWareFreight(finishedCallback:@escaping () ->())  {
        var timerStr:String = ""
        if orderInfoModel.orderType != 2 {
            timerStr = orderInfoModel.standardTimerValue
        } else {
            timerStr = orderInfoModel.expectedDeliveryTime
        }
        if orderInfoModel.goodsName.count > 0 && timerStr.count > 0 {
            let dicData = ["expectedDays":(orderInfoModel.expectedDays),"expectedDeliveryTime":timerStr] as [String : Any]
            HttpService.sharedHttpService().getCalculateWareFreight(dicData: dicData) { (json, state, error) in
                Constants.window?.hideAllToasts()
                Constants.window?.hideToastActivity()
                if state {
                    let jsonData:Dictionary = json["data"].dictionary ?? Dictionary()
                    self.orderInfoModel.warehouseFreight = jsonData["warehousingCost"]?.description ?? ""
                    self.boottomView.valueLab.text = "MMK" + self.orderInfoModel.getTotalFreight()
                    finishedCallback()
                } else {
                    Constants.window?.makeToast(error)
                }
            }
        }
    }
    
    func spotprintInfoCell(cell: SpotInformationCell, clickType: SpotInfoCellType) {
        if clickType != SpotInfoCellType.Spot_InfoMsg_Type {
            if sendInfoModel.name.isEmpty || receiveInfoModel.name.isEmpty {
                Constants.window?.makeToast(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_hint_import_addressMsg))
                return
            }
        }
        
        switch clickType {
        case SpotInfoCellType.Spot_InfoMsg_Type:
            let InformationC:InformationController = InformationController.init()
            InformationC.informationBlock = {
                self.getFreightValueSuccess { (state) in
                    self.tableview.reloadData()
                    self.textFieldDidChange()
                }
            }
            InformationC.setOrderListModel(orderInfoModel: orderInfoModel)
            self.navigationController?.pushViewController(InformationC, animated: true)
            break
        case SpotInfoCellType.Spot_PayMsg_Type :
            if orderInfoModel.deliveryWay != 0 {
                Constants.window?.makeToast(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_hint_station_paid))
            } else {
                Constants.window?.addSubview(self.selectPayView)
            }
            break
            
        case SpotInfoCellType.Spot_TimerMsg_Type :
            if orderInfoModel.deliveryWay != 0 {
                Constants.window?.makeToast(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_hint_station_timer))
            } else {
                Constants.window?.addSubview(self.selectTimerV)
            }
            break
            
        case SpotInfoCellType.Spot_Delivery_Type :
            Constants.window?.addSubview(self.selectDeliveryV)
            break
        default:
            break
        }
    }
    
    func SpotBoottomViewClickedType(clickType: SpotInfoCellType) {
        switch clickType {
        case SpotInfoCellType.Spot_Print_Type:
            if sendInfoModel.name.count <= 0 || receiveInfoModel.name.count <= 0 {
                Constants.window?.makeToast(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_hint_import_addressMsg))
                return
            }
            if orderInfoModel.goodsName.count <= 0 {
                Constants.window?.makeToast(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.spot_hint_import_information))
                return
            }
            self.printingOrder()
            break
        case SpotInfoCellType.Spot_ShowDetail_Type:
            if sendInfoModel.name.count <= 0 || receiveInfoModel.name.count <= 0 {
                Constants.window?.makeToast(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_hint_import_addressMsg))
                return
            }
            if orderInfoModel.goodsName.count <= 0 {
                Constants.window?.makeToast(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.spot_hint_import_information))
                return
            }
            Constants.window?.addSubview(self.lookBillV)
            break
        default:
            break
        }
    }
    
    func SpotSubjoinServeClickedType(clickType: SpotInfoCellType) {
        switch clickType {
        case SpotInfoCellType.Spot_Protect_Type:
            Constants.window?.addSubview(self.supportValueV)
            break
        case SpotInfoCellType.Spot_Collection_Type:
            Constants.window?.addSubview(self.selectCollectionV)
            break
        default:
            break
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if orderInfoModel.deliveryWay != 0 {
            return 3
        }
        return 4
    }
    
    func tableView(_ tableView: UITableView, heightForRowAtIndexPath section: Int) -> CGFloat {
        tableView.rowHeight = UITableView.automaticDimension
        tableview.estimatedRowHeight = 100
        return tableview.rowHeight
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell:SpotAddressCell = tableview.dequeueReusableCell(withIdentifier: SpotAddressIdentifier) as! SpotAddressCell
            cell.spotAddressCellBlock = {
                let addressListC:AddressListController = AddressListController.init()
                addressListC.setIndex(index: 1)
                addressListC.selectAddressBlock = { (userAddressModel,index) in
                    self.sendInfoModel = userAddressModel
                    self.getFreightValueSuccess { (state) in
                        self.tableview.reloadData()
                        self.textFieldDidChange()
                    }
                }
                self.navigationController?.pushViewController(addressListC, animated: true)
            }
            cell.setValueWithClientInfoModel(InfoMode: sendInfoModel, addressType: SpotAddressType.SpotAddressSentType)
            return cell
        } else if indexPath.row == 1 {
            let cell:SpotAddressCell = tableview.dequeueReusableCell(withIdentifier: SpotAddressIdentifier) as! SpotAddressCell
            cell.spotAddressCellBlock = {
                let addressListC:AddressListController = AddressListController.init()
                addressListC.setIndex(index: 2)

                addressListC.selectAddressBlock = { (userAddressModel,index) in
                    self.receiveInfoModel = userAddressModel
                    if userAddressModel.supportDelivery {
                        self.orderInfoModel.payType = 0
                        self.orderInfoModel.deliveryWay = 1
                        self.orderInfoModel.supportDelivery = false
                        self.orderInfoModel.isInsure = 0;
                        self.orderInfoModel.isCollection = 0;
                        self.orderInfoModel.collectionFreightAmount = "";
                        self.orderInfoModel.insureAmount = "";
                        self.orderInfoModel.insureFreight = 0;
                    }
                    self.getFreightValueSuccess { (state) in
                        self.tableview.reloadData()
                        self.textFieldDidChange()
                    }
                }
                self.navigationController?.pushViewController(addressListC, animated: true)
            }
            cell.setValueWithClientInfoModel(InfoMode: sendInfoModel, addressType: SpotAddressType.SpotAddressSentType)
            return cell
        } else if indexPath.row == 2 {
            spotInfocell = tableview.dequeueReusableCell(withIdentifier: SpotInformationIdentifier) as! SpotInformationCell
            spotInfocell.setOrderListModel(orderInfoModel: orderInfoModel)
            spotInfocell.selectionStyle = UITableViewCell.SelectionStyle.none
            spotInfocell.delegate = self
            return spotInfocell
        } else {
            let cell:SpotSubjoinServeCell = tableview.dequeueReusableCell(withIdentifier: SpotSubjoinServeIdentifier) as! SpotSubjoinServeCell
            cell.setOrderInfoModel(orderInfoModel: orderInfoModel)
            cell.delegate = self
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableview.deselectRow(at: indexPath, animated: true)
        if indexPath.row == 0 || indexPath.row == 1 {
            let userAddressVC:EditAddressController = EditAddressController.init()
            userAddressVC.addressType = indexPath.row == 0 ? 1 : 2
            userAddressVC.selectAddressBlock = {(userAddressModel,index) in
                if indexPath.row == 0 {
                    self.sendInfoModel = userAddressModel
                } else {
                    self.receiveInfoModel = userAddressModel
                    if userAddressModel.supportDelivery {
                        let roleType = WLUserModel.getRoleType()
                        if roleType.contains(where: { (obj) -> Bool in
                            if obj as! Int == 7 {
                                self.orderInfoModel.payType = 3
                                return true
                            } else {
                                return false
                            }
                        }) {
                            
                        }
                        self.orderInfoModel.deliveryWay = 1
                        self.orderInfoModel.supportDelivery = false
                        self.orderInfoModel.isInsure = 0;
                        self.orderInfoModel.isCollection = 0;
                        self.orderInfoModel.collectionFreightAmount = "";
                        self.orderInfoModel.insureAmount = "";
                        self.orderInfoModel.insureFreight = 0;
                    }
                }
                
                self.getFreightValueSuccess { (state) in
                    self.tableview.reloadData()
                    self.textFieldDidChange()
                }
            }
            userAddressVC.setAddressModel(addressModel: indexPath.row == 0 ? self.sendInfoModel : self.receiveInfoModel)
            self.navigationController?.pushViewController(userAddressVC, animated: true)
        }
    }
    
    func printingOrder()  {
        self.orderInfoModel.synchClientInfoModelInfo(clientInfoModel: sendInfoModel, isReceive: false)
        self.orderInfoModel.synchClientInfoModelInfo(clientInfoModel: receiveInfoModel, isReceive: true)
        if orderInfoModel.payType == 2 {
            if orderInfoModel.collectionFreightAmount <= orderInfoModel.getTotalFreight() {
                Constants.window?.makeToast(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.spot_hint_deductionInsufficient))
                return
            }
        }
        Constants.window?.makeToastActivity(.center)
        HttpService.sharedHttpService().generateOrder(orderInfo: orderInfoModel) { (json, state, error) in
            Constants.window?.hideToastActivity()
            if state {
                let jsonData:Dictionary = json["data"].dictionary ?? Dictionary()
                let sportStateC:SportStateController = SportStateController.init()
                sportStateC.mailSn = jsonData["mailSn"]?.string ?? ""
                sportStateC.orderSn = jsonData["orderSn"]?.string ?? ""
                self.orderInfoModel = OrderListModel.init()
                self.receiveInfoModel = AddressModel.init()
                self.lookBillV.setOrderInfoModel(orderInfoModel: self.orderInfoModel)
                self.textFieldDidChange()
                self.boottomView.valueLab.text = ""
                self.tableview.reloadData()
                self.navigationController?.pushViewController(sportStateC, animated: true)
            } else {
                Constants.window?.makeToast(error)
            }
        }
    }
    
    lazy var selectCollectionV: SpotSelectCollectionView = {
        let selectCollectionV = SpotSelectCollectionView.init(frame: CGRect.init(x: 0, y: 0, width: Constants.screenWidth, height: Constants.screenHeight))
        selectCollectionV.spotCollectionValueBlock = { (collectionValue) in
            self.orderInfoModel.collectionFreightAmount = collectionValue
            if collectionValue.count > 0 {
                self.orderInfoModel.isCollection = 1
            } else {
                self.orderInfoModel.isCollection = 0
            }
            self.textFieldDidChange()
            self.tableview.reloadData()
        }
        return selectCollectionV
    }()
    
    lazy var selectDeliveryV: SpotSelectDeliveryView = {
        let selectDeliveryV = SpotSelectDeliveryView.init(frame: CGRect.init(x: 0, y: 0, width: Constants.screenWidth, height: Constants.screenHeight))
        selectDeliveryV.spotDeliveryValueBlock = {
            self.getFreightValueSuccess { (state) in
                self.tableview.reloadData()
                self.textFieldDidChange()
                self.lookBillV.setOrderInfoModel(orderInfoModel: self.orderInfoModel)
            }
            self.tableview.reloadData()
            self.textFieldDidChange()
        }
        orderInfoModel.supportDelivery = receiveInfoModel.supportDelivery
        selectDeliveryV.setOrderInfoModel(orderInfoModel: self.orderInfoModel)
        return selectDeliveryV
    }()
    lazy var selectTimerV: SpotSelectTimerView = {
        let selectTimerV = SpotSelectTimerView.init(frame: CGRect.init(x: 0, y: 0, width: Constants.screenWidth, height: Constants.screenHeight))
        selectTimerV.spotSelectTimerViewBlock = {
            self.getFreightValueSuccess { (state) in
                self.getcalculateWareFreight {
                    
                }
                self.tableview.reloadData()
                self.textFieldDidChange()
            }
            self.tableview.reloadData()
            self.textFieldDidChange()
        }
        selectTimerV.setOrderInfoModel(orderInfoModel: self.orderInfoModel)
        return selectTimerV
    }()
    lazy var selectPayView: SpotSelectPayView = {
        let selectPayView = SpotSelectPayView.init(frame: CGRect.init(x: 0, y: 0, width: Constants.screenWidth, height: Constants.screenHeight))
        selectPayView.spotSelectPayConfirmBlock = {
            self.tableview.reloadData()
            self.textFieldDidChange()
        }
        selectPayView.setOrderInfoModel(orderInfoModel: orderInfoModel)
        return selectPayView
    }()
    
    lazy var lookBillV: SpotLookBillView = {
        let lookBillV = SpotLookBillView.init(frame: CGRect.init(x: 0, y: 0, width: Constants.screenWidth, height: Constants.screenHeight))
        lookBillV.setOrderInfoModel(orderInfoModel: orderInfoModel)
        return lookBillV
    }()
    
    lazy var boottomView: SpotBoottomView = {
        let boottomView:SpotBoottomView = Bundle.main.loadNibNamed("SpotBoottomView", owner: self, options: nil)?.first as! SpotBoottomView
        boottomView.delegate = self
        return boottomView
    }()
    
    lazy var supportValueV: SpotSupportValueView = {
        let supportValueV = SpotSupportValueView.init(frame: CGRect.init(x: 0, y: 0, width: Constants.screenWidth, height: Constants.screenHeight))
        supportValueV.supportValueBlock = {
            self.boottomView.valueLab.text = "MMK" + self.orderInfoModel.getTotalFreight()
            self.tableview.reloadData()
            self.textFieldDidChange()
        }
        supportValueV.setOrderInfoModel(orderInfoModel: self.orderInfoModel)
        return supportValueV
    }()
    lazy var sendInfoModel:AddressModel  = {
        let sendInfoModel = AddressModel()
        return sendInfoModel
    }()
    
    lazy var receiveInfoModel:AddressModel  = {
        let receiveInfoModel = AddressModel()
        return receiveInfoModel
    }()
    
    lazy var orderInfoModel:OrderListModel = {
        let orderInfoModel = OrderListModel()
        let roleType = WLUserModel.getRoleType()
        if roleType.contains(where: { (obj) -> Bool in
            if obj as! Int == 7 {
                orderInfoModel.payType = 3
                return true
            } else {
                return false
            }
        }) {
            
        }
        return orderInfoModel
    }()

    lazy var tableview: UITableView = {
        let tableview:UITableView = UITableView.init()
        tableview.showsVerticalScrollIndicator = false
        tableview.delegate = self
        tableview.dataSource = self
        tableview.keyboardDismissMode = .onDrag
        tableview.separatorStyle = .none
        tableview.backgroundColor = UIColor.init(hexString: "#F3F3F3")
        tableview.register(UINib.init(nibName: "SpotInformationCell", bundle: nil), forCellReuseIdentifier: SpotInformationIdentifier)
        tableview.register(UINib.init(nibName: "SpotAddressCell", bundle: nil), forCellReuseIdentifier: SpotAddressIdentifier)
        tableview.register(UINib.init(nibName: "SpotSubjoinServeCell", bundle: nil), forCellReuseIdentifier: SpotSubjoinServeIdentifier)
        return tableview
    }()

}
